<template>
  <ContainerLayout class="human-statistics">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="部门">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.timelogCategory" placeholder="选择" style="width: 80px">
            <el-option label="全部" value="" />
            <el-option v-for="item in projectTypes" :key="item.dictCode" :label="`${item.dictLabel}`" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" v-if="queryForm.timelogCategory === '0'">
          <el-select v-model="queryForm.projectId" placeholder="请选择项目" style="width: 160px">
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-tabs v-model="tabsActiveName" class="demo-tabs" @tab-click="handleClickTabs" editable>
        <el-tab-pane v-for="(item, idx) in deptTags" :key="idx" :label="item.deptName" :name="item.deptName" />
      </el-tabs>
      <template v-if="isQueryed">
        <template v-if="tableData.length">
          <div class="table-title">{{ projectTitle }}</div>
          <div class="table-wrap" ref="tableWrap">
            <el-table ref="dataTable" :data="tableData" style="width: 100%" border show-summary scrollbar-always-on :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
              <el-table-column label="姓名" width="120" fixed>
                <template #default="scope"> {{ scope.row.userNick }}</template>
              </el-table-column>
              <el-table-column label="职务" width="180" fixed>
                <template #default="scope"> {{ scope.row.posts }}</template>
              </el-table-column>
              <template v-for="item in tableColumnDate">
                <el-table-column :prop="item.label" width="70" resizable>
                  <template #header>
                    <div class="table-header-cell">
                      <div>{{ item.label }}</div>
                      <!-- <div>{{ item.end }}</div> -->
                    </div>
                  </template>
                  <template #default="scope">
                    {{ scope.row[item.columnName + ':val'] }}
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
        </template>
        <template v-else>
          <div class="table-title" v-if="projectTitle !== ''">{{ projectTitle }}</div>
          <el-empty description="没有查询到符合条件的数据" />
        </template>
      </template>
      <template v-else>
        <el-empty description="尚未查询数据" />
      </template>
    </div>
  </ContainerLayout>
</template>
<script setup lang="ts">
import ContainerLayout from '../layout/ContainerLayout.vue'
import { Refresh, Search } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, nextTick } from 'vue'
import IProjectTypes from '../interface/IProjectTypes'
import { useDeptStore, useProjectssStore, useTaskTypeStore } from '../stores'
import * as utils from '../utils'
import http from '../http'
import { ElMessage } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'

const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const projectTypes = ref<IProjectTypes[]>(useTaskTypeStore().getAllState())
const deptList = ref(useDeptStore().getAllState())
const deptTags = ref<any>([])
const isQueryed = ref(false)
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(useProjectssStore().getAllState() as any)
const tableData = ref<any[]>([])
const projectTitle = ref<string>('')
const tableHeight = ref(500)
const tableColumnDate = ref<any[]>([])
const tableWrap = ref<HTMLElement | null>(null)
const tabsActiveName = ref<any>('')
const queryRows = ref<any[]>([])

const queryForm = reactive({
  projectId: '',
  date: [] as Date[],
  deptIds: [] as string[] | number[],
  timelogCategory: '',
})

/**
 * 提交表单处理函数
 *
 * @returns {Promise<void>} 返回一个异步操作的Promise对象，无返回值
 */
const handleClickBtnSubmit = async () => {
  // console.log('queryForm', queryForm)
  isQueryed.value = true
  tableData.value = []
  projectTitle.value = ''
  if (queryForm.date.length == 2) {
    await getDataList()
  }
}
/**
 * 重置按钮点击事件处理函数
 *
 * @returns 无返回值
 */
const handleClickBtnReset = async () => {
  await resetForm()
}

/**
 * 异步获取数据
 *
 * @param startTimelogDate 开始时间
 * @param endTimelogDate 结束时间
 * @returns 返回数据行
 */
const fetchData = async (startTimelogDate: any, endTimelogDate: any) => {
  projectTitle.value = `${startTimelogDate} - ${endTimelogDate} 项目统计`
  const params = {
    startTimelogDate,
    endTimelogDate,
  }
  const deptIds: any[] = []
  queryForm.deptIds.forEach((e: any) => {
    deptIds.push(e[e.length - 1])
  })
  if (deptIds.length > 0) {
    Object.assign(params, { deptIds: deptIds.join(',') })
  }
  if (queryForm.timelogCategory !== '') {
    Object.assign(params, { timelogCategory: queryForm.timelogCategory })
  }
  if (queryForm.timelogCategory === '0' && queryForm.projectId !== '') {
    Object.assign(params, { projectId: queryForm.projectId })
    const projectItem = projectList.value.find((e: any) => e.id == queryForm.projectId)
    if (projectItem) {
      projectTitle.value = `${projectItem.code}-${projectItem.cname} ` + projectTitle.value
    }
  }
  if (queryForm.timelogCategory === '0' && queryForm.projectId === '') {
    ElMessage.error('必须选择项目')
    return
  }
  const res = await http({
    method: 'GET',
    path: '/dev-api/oa/hrm/listbydept',
    params,
  })
  const { rows } = res
  return rows
}

const getDataList = async () => {
  if (queryForm.date.length == 2) {
    const [start, end] = queryForm.date
    // console.log(projectList.value)
    // const showTypeItem = tableTypeList.value[showType.value]

    const weeks = utils.getWeeksBetweenDates(start, end)
    const [first] = weeks
    const [last] = weeks.slice(-1)
    const startTimelogDate = utils.formatDate(first.start, 'yyyy-MM-dd')
    const endTimelogDate = utils.formatDate(last.end, 'yyyy-MM-dd')

    // 设置 table 列
    tableColumnDate.value = [
      ...weeks.map((e) => {
        const start = utils.formatDate(e.start, 'yyyy-MM-dd')
        const end = utils.formatDate(e.end, 'yyyy-MM-dd')
        const startYear = utils.formatDate(e.start, 'yyyy')
        const endYear = utils.formatDate(e.end, 'yyyy')
        const startDay = utils.formatDate(e.start, 'MM-dd')
        const endDay = utils.formatDate(e.end, 'MM-dd')
        return { key: start, dataKey: start, title: start, width: 150, label: start, columnName: `${start} - ${end}`, start, end, startDay, endDay, startYear, endYear }
      }),
    ]
    // minutes 每天工作时长 （长春 400 分钟）
    // 一周 5 天
    // const weekMinutes = minutes * 5 // 一周 工作 5 天 时长

    queryRows.value = await fetchData(startTimelogDate, endTimelogDate)
    await dataFilterAndBind()
  }
}
/**
 * 异步函数，用于数据过滤和绑定到表格
 *
 * @returns 返回一个Promise对象，该对象在数据绑定到表格后解析
 */
const dataFilterAndBind = async () => {
  const rows = queryRows.value.filter((e: any) => e.deptName == tabsActiveName.value)
  const result: any = {}
  rows.forEach((row: any) => {
    // row.push
    // deptId,deptName,parentDeptName,userSum
    const key = `${row.deptId}-${row.deptName}-${row.userNick}`
    if (!result[key]) {
      let posts = ''
      if (row.posts.length) {
        posts = row.posts.map((item: any) => item.postName).join('/')
      }
      result[key] = {
        ...row,
        posts,
      }
    }
  })
  for (const key in result) {
    const e = result[key]
    for (let index = 0; index < tableColumnDate.value.length; index++) {
      const temp = tableColumnDate.value[index]
      //
      if (!e[temp.columnName]) {
        e[temp.columnName] = 1
      }
      // const colVal = (e[temp.columnName] * 1000) / workingHours.value / currentShowTypeItem.value.days
      e[temp.start] = 1
      e[temp.columnName] = 1
      e[temp.columnName + ':val'] = 1
    }
  }
  // console.log('result', result)
  await bindDataToTable(Object.values(result))
}
/**
 * 将数据绑定到表格中
 *
 * @param data 要绑定到表格的数据
 * @returns 无返回值
 */
const bindDataToTable = async (data: any) => {
  tableData.value = data
  nextTick(() => {
    const tableWrapElement = tableWrap.value
    if (tableWrapElement) {
      // 设置表格高度
      tableHeight.value = tableWrapElement.offsetHeight
      // 延迟执行，等待表格渲染完成后再设置
      setTimeout(() => {
        if (tableWrapElement) {
          // 表格的最后一行前两个单元格合并
          const tds = tableWrapElement.querySelectorAll('.el-table__footer td')
          const tbs0 = tds[0] as HTMLElement
          tbs0.setAttribute('colspan', '2')
          tbs0.style.textAlign = 'center'
          tds[1].remove()
        }
      }, 200)
    }
  })
}

const handleClickTabs = async (tab: TabsPaneContext, ) => {
  // console.log(tab.props.name, event)
  // console.log(tabsActiveName.value)
  tabsActiveName.value = tab.props.name

  await dataFilterAndBind()
}

const initDeptIds = async () => {
  // console.log('deptList', deptList.value[0].children[0].children)
  const ids: any = []
  deptList.value[0].children[0].children.forEach((item: any) => {
    ids.push(item.ancestors.split(',').map(Number).slice(1).concat(item.deptId))
    deptTags.value.push({ ...item, checked: false })
  })
  tabsActiveName.value = deptTags.value[0].deptName
  queryForm.deptIds = ids
}
/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门ID数组和时间日志类别
 */
const resetForm = () => {
  isQueryed.value = false
  tableData.value = []
  projectTitle.value = ''
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.前后半年) as Date[]
  queryForm.projectId = ''
  queryForm.date = [start, end]
  queryForm.timelogCategory = ''
  nextTick(() => {
    // 重置部门树
    initDeptIds()
    handleClickBtnSubmit()
  })
}

onMounted(async () => {
  await handleClickBtnReset()
})
</script>
<style lang="scss" scoped>
.human-statistics {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .table-header-cell {
    writing-mode: vertical-lr;
    // line-height: 1;
  }
}
</style>
